//
//  EvaluateTableViewCell.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/8/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import AVFoundation
import AssetsLibrary
import Photos
import PhotosUI
import MobileCoreServices
import SwiftyJSON

protocol EvaluateTableViewCellDelegate: NSObjectProtocol {
    func updateDate(model:EvaluateModel,index:Int)
}
class EvaluateTableViewCell: UITableViewCell,UITextViewDelegate,UploadImgCollectionViewCellDelegate,ImageCollectionViewCellDelegate,UICollectionViewDelegate, UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    @IBOutlet weak var goodsName: UILabel!
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var spec: UILabel!
    @IBOutlet weak var topRatingView: LCStarRatingView!
    @IBOutlet weak var centerRatingView: LCStarRatingView!
    @IBOutlet weak var bottomRatingView: LCStarRatingView!
    @IBOutlet weak var topLabel: UILabel!
    @IBOutlet weak var centerLabel: UILabel!
    @IBOutlet weak var bottomLabel: UILabel!
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var countNum: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    weak var delegate: EvaluateTableViewCellDelegate?
    var model:purcharseModel?
    var comment:EvaluateModel = EvaluateModel()
    var imgArr:[UIImage] = []
    var imgIds:[String] = []
    var jointId:String = ""
    var itemWidth: CGFloat?
    var index:Int = 0
    override func awakeFromNib() {
        super.awakeFromNib()
//        setShadow(view: mainScrollView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        let ratings = [topRatingView, centerRatingView, bottomRatingView]
        self.textView.delegate = self
        let _ = ratings.map({
            $0?.progress = 5
            $0?.starColor = UIColor(hex: 0x838383)
            $0?.starPlaceHolderColor = UIColor.white
            $0?.starPlaceHolderBorderColor = UIColor(hex: 0x838383)
            $0?.starPlaceHolderBorderWidth = 1
        })
        
        topRatingView.progress = 5
        topRatingView.progressDidChangedByUser = ({[weak self] value in
            self?.comment.predictabilityGrade = String(describing: value)
            self?.topLabel.text = self?.titleType(value)
            self?.delegate?.updateDate(model: (self?.comment)!, index: (self?.index)!)
        })
        centerRatingView.progress = 5
        centerRatingView.progressDidChangedByUser = ({[weak self] value in
            self?.comment.beautyGrade = String(describing: value)
            self?.centerLabel.text = self?.titleType(value)
            self?.delegate?.updateDate(model: (self?.comment)!, index: (self?.index)!)
        })
        bottomRatingView.progress = 5
        bottomRatingView.progressDidChangedByUser = ({[weak self] value in
            self?.comment.costGrade = String(describing: value)
            self?.bottomLabel.text = self?.titleType(value)
            self?.delegate?.updateDate(model: (self?.comment)!, index: (self?.index)!)
        })
        collectionView.collectionViewLayout = getFlowLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib.init(nibName: "\(UploadImgCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(UploadImgCollectionViewCell.self)")
        collectionView.register(UINib.init(nibName: "\(ImageCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(ImageCollectionViewCell.self)")
        collectionView.reloadData()
    }
    
    func getFlowLayout() -> UICollectionViewFlowLayout {
        var flowLayout = UICollectionViewFlowLayout()
        
        flowLayout = UICollectionViewFlowLayout()
        let itemSize = self.contentView.width / 3
        self.itemWidth = itemSize
        flowLayout.itemSize = CGSize(width: itemSize, height: itemSize)
        flowLayout.scrollDirection = .vertical
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        return flowLayout
    }
    
    func setData(commentModel:EvaluateModel) {
        self.comment = commentModel
        goodsName.text = self.model?.goodsName
        spec.text = self.model?.specAndCol
        img.sd_setImage(with: appendUrl(suffix: (self.model?.imageUrl)!), completed: nil)
        let a:Float = Float(comment.predictabilityGrade!)!
        let b:Float = Float(comment.beautyGrade!)!
        let c:Float = Float(comment.costGrade!)!
        topRatingView.progress = CGFloat.init(a)
        centerRatingView.progress = CGFloat.init(b)
        bottomRatingView.progress = CGFloat.init(c)
        textView.text = comment.commentContent
        jointId = comment.jointId!
        imgIds = comment.imgIds!
        self.imgArr = comment.imgArr!
        collectionView.reloadData()
    }
    
    private func titleType(_ value: CGFloat) -> String {
        switch value {
        case 1:
            return "非常差"
        case 2...4:
            return "一般"
        case 5:
            return "非常满意"
        default:
            break
        }
        return ""
    }

    public func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count > 0 {
            
            //获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange
            
            //获取高亮部分 － 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = textView.text
            let textNum = textContent?.characters.count
            
            //截取200个字
            if textNum! > 300 {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: 300)
                let str = textContent?.substring(to: index!)
                textView.text = str
            }
        }
        self.countNum.text =  "\(textView.text.characters.count)/\(300)"
        self.comment.commentContent = textView.text
        self.delegate?.updateDate(model: comment, index: index)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func addImage() {
        if self.imgArr.count == 5 {
            return
        }
        let alertController:UIAlertController = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let takePhotoAction:UIAlertAction = UIAlertAction.init(title: "拍照", style: UIAlertActionStyle.default) { (action) in
            self.takePhoto()
        }
        
        let choosePhotoAction:UIAlertAction = UIAlertAction.init(title: "相册", style: UIAlertActionStyle.default) { (action) in
            self.selectPhoto()
        }
        
        let cancelAction:UIAlertAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (action) in
        }
        alertController.addAction(takePhotoAction)
        alertController.addAction(choosePhotoAction)
        alertController.addAction(cancelAction)
        UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true)
    }
    
    func delIamge(cell: ImageCollectionViewCell) {
        let indexPath = self.collectionView.indexPath(for: cell)
        self.imgArr.remove(at: (indexPath?.item)!)
        let imgId:String = self.imgIds[(indexPath?.item)!]
        delImagereq(id: imgId)
        self.imgIds.remove(at: (indexPath?.item)!)
        self.collectionView.deleteItems(at: [indexPath!])
        self.comment.imgIds = self.imgIds
        self.comment.imgArr = self.imgArr
        self.delegate?.updateDate(model: comment, index: index)
    }
    
    func delImagereq(id:String) {
        let requesturl = appendUrl(suffix: deleteFielUrl + "/" + id)
        Alamofire.request(requesturl, method: .post,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            
        }
    }
    
    func addImageCallBak(image:UIImage,jointId:String,imgId:String) -> Void {
        if self.jointId == "" {
            self.jointId = jointId
            self.comment.jointId = jointId
        }
        self.imgIds.insert(imgId, at: 0)
        self.comment.imgIds = self.imgIds
        self.delegate?.updateDate(model: comment, index: index)
    }
    
    func addImageToItem(image:UIImage) {
        self.imgArr.insert(image, at: 0)
        self.comment.imgArr = self.imgArr
        let indexPath = IndexPath.init(item: 0, section: 0)
        self.collectionView.insertItems(at: [indexPath])
    }
    
    // MARK: - CollectionViewDatasource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imgArr.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == self.imgArr.count + 1 - 1 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(UploadImgCollectionViewCell.self)", for: indexPath) as! UploadImgCollectionViewCell
            cell.delegate = self
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(ImageCollectionViewCell.self)", for: indexPath) as! ImageCollectionViewCell
            cell.delegate = self
            cell.img.image = self.imgArr[indexPath.item]
            return cell
        }
    }
    
    func takePhoto() {
        let imagePickerController:UIImagePickerController = UIImagePickerController.init()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
        imagePickerController.allowsEditing = false
        imagePickerController.showsCameraControls = true
        imagePickerController.videoQuality = UIImagePickerControllerQualityType.typeIFrame1280x720
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear
        imagePickerController.mediaTypes = [kUTTypeImage as String]
        UIApplication.shared.keyWindow?.rootViewController?.present(imagePickerController, animated: true)
    }
    
    func selectPhoto() {
        let imagePickerController:UIImagePickerController = UIImagePickerController.init()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePickerController.allowsEditing = false
        imagePickerController.mediaTypes = [kUTTypeImage as String]
        UIApplication.shared.keyWindow?.rootViewController?.present(imagePickerController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType:String = info[UIImagePickerControllerMediaType] as! String
        if mediaType == kUTTypeImage as String {
            let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            self.addImageToItem(image: image)
            self.uploadImage(img: image)
            picker.dismiss(animated: true)
        }
    }
    
    func uploadImage(img:UIImage) {
        let upload:MMFileUploadUtil = MMFileUploadUtil.init()
        upload.uploadFile(with: UIImageJPEGRepresentation(img, 0), fs: "5", jointId: self.jointId) { (response, error) in
            if (error != nil) {
                return
            }
            let sudi: NSDictionary? = response as? NSDictionary
            let json = JSON(sudi)
            let joindata = json["data"].dictionary
            let joint = joindata!["jointId"]
            let imgId:String = (joindata!["id"]?.number?.stringValue)!
            self.addImageCallBak(image: img, jointId: (joint?.string)!, imgId:imgId)
        }
    }
}
